package com.example.leetcode.design;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class WordDistance {

    Map<String, List<Integer>> indexMap;

    public WordDistance(String[] wordsDict) {
        this.indexMap = new HashMap<>();
        for (int i = 0; i < wordsDict.length; i++) {
            indexMap.putIfAbsent(wordsDict[i], new ArrayList<>());
            indexMap.get(wordsDict[i]).add(i);
        }
    }

    public int shortest(String word1, String word2) {
        int result = Integer.MAX_VALUE;
        List<Integer> posList1 = indexMap.get(word1);
        List<Integer> posList2 = indexMap.get(word2);
        int index1 = 0;
        int index2 = 0;
        while (index1 < posList1.size() && index2 < posList2.size()) {
            int lastPos1 = posList1.get(index1);
            int lastPos2 = posList2.get(index2);
            if (lastPos1 < lastPos2) {
                result = Math.min(lastPos2 - lastPos1, result);
                index1++;
            } else if (lastPos1 > lastPos2) {
                result = Math.min(lastPos1 - lastPos2, result);
                index2++;
            }
        }
        return result;
    }
}

/**
 * Your WordDistance object will be instantiated and called as such:
 * WordDistance obj = new WordDistance(wordsDict);
 * int param_1 = obj.shortest(word1,word2);
 */

public class leetcode244 {
    public static void main(String[] args) {
        String[] wordDict = {"practice", "makes", "perfect", "coding", "makes"};
        WordDistance wordDistance = new WordDistance(wordDict);
        System.out.println(wordDistance.shortest("coding", "practice")); // 返回 3
        System.out.println(wordDistance.shortest("makes", "coding"));    // 返回 1
    }
}
